import { getExtByName } from '@/utils/helper'
import { BusiFileTypes, FileTypes } from './fileType'
export async function chooseImageInApp(params = {}) {
  console.log('chooseImageInApp', params)
  window.yyn.registryMethod('chooseImageAndFile', '2.0.7')
  return new Promise((resolve, reject) => {
    window.yyn.app.invoke(
      'chooseImageAndFile',
      params,
      (error) => reject(error),
      (payload) => {
        console.log('App回传的数据', payload)
        const { imageList = [], fileList = [] } = payload
        const formatFile = (f) => {
          return f.map((item) => {
            const ext = getExtByName(item.name || item.url)
            console.log(ext)
            const type = FileTypes.图片.includes(ext)
              ? BusiFileTypes.图片
              : FileTypes.视频.includes(ext)
              ? BusiFileTypes.视频
              : FileTypes.音频.includes(ext)
              ? BusiFileTypes.音频
              : BusiFileTypes.其他
            return {
              type,
              url: item.url,
              original: item.name,
              mime: item.mime,
              size: item.size
            }
          })
        }
        console.log(formatFile(imageList))
        console.log(formatFile(fileList))
        const result = formatFile(imageList).concat(formatFile(fileList))
        console.log('format结果', result)
        resolve(result)
      }
    )
  })
}

export async function chooseImageUpload(payload) {
  console.log('chooseImageUpload分发')
  try {
    const res = await chooseImageInApp(
      payload
        ? { imageMaxCount: payload.maxImage, fileMaxCount: payload.maxFile }
        : {}
    )
    return res
  } catch (e) {
    console.error(e)
  }
}
